<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card class="box-card">
      <!-- 搜索区域 -->
      <el-row :gutter="20">
        <el-col :span="13">
          <!-- v-model双向绑定 -->
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            clearable
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="7">
          <el-button type="primary" @click="addDialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>
      <!-- 内容区域 -->
      <el-table :data="userList" style="width: 100%" stripe border>
        <el-table-column type="index" label="#"> </el-table-column>
        <el-table-column prop="username" label="姓名"> </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <!-- 按钮开关 -->
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="userStateChanged(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <!-- 操作栏 -->
        <el-table-column label="操作" width="175px">
          <template slot-scope="scope">
            <!-- 修改 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row.id)"
            ></el-button>
            <!-- 删除 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeUserById(scope.row.id)"
            ></el-button>
            <!-- 第三个小黄标 -->
            <el-tooltip
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="setRole(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 底部页尾 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 4, 6, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
      <!-- 添加框的区域 -->
      <el-dialog
        title="注册用户"
        :visible.sync="addDialogVisible"
        width="50%"
        @close="addDialogClose"
      >
        <!-- 内容主体 -->
        <el-form
          :model="addFrom"
          :rules="addFromRules"
          ref="addFromRef"
          label-width="70px"
        >
          <el-form-item label="账号" prop="username">
            <el-input v-model="addFrom.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addFrom.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addFrom.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="addFrom.mobile"></el-input>
          </el-form-item>
        </el-form>
        <!-- 底部区域 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 修改框的区域 -->
      <el-dialog
        title="修改用户"
        :visible.sync="editDialogVisible"
        width="50%"
        @close="etitDialogClosed"
      >
        <!-- 文本框 -->
        <el-form
          :model="editForm"
          :rules="editFormRules"
          ref="editFormRef"
          label-width="70px"
        >
          <el-form-item label="用户名">
            <el-input v-model="editForm.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="editForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editUserInfo">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 分配角色区域 -->
      <el-dialog title="分配角色" @close="setRoleDialogClose" :visible.sync="setRoleDialogVisible" width="30%">
        <div>
          <p>用户名称：{{ userInfo.username }}</p>

          <p>当前角色：{{ userInfo.role_name }}</p>
          <p>
            分配新角色：
            <el-select v-model="selectedRoleId" placeholder="请选择">
              <el-option
                v-for="item in rolesList"
                :key="item.id"
                :label="item.roleName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </p>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="setRoleDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveRoleInfo"
            >确 定</el-button
          >
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    // 自定义邮箱规则
    const checkEmail = (rule, value, cd) => {
      const regEmail =
        /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$/
      if (regEmail.test(value)) {
        return cd()
      }
      cd(new Error('请输入合法邮箱'))
    }
    // 自定义手机号规则
    const checkMobile = (rule, value, cd) => {
      const regMobile =
        /^1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[89])\d{8}$/
      if (regMobile.test(value)) {
        return cd()
      }
      cd(new Error('请输入合法手机号'))
    }

    return {
      queryInfo: {
        //用户输入的数值
        query: '',
        //页数
        pagenum: 1,
        //每页有多少条
        pagesize: 2,
      },
      userList: [],
      total: 0,
      addDialogVisible: false,
      // 添加表单数据
      addFrom: {
        username: '',
        password: '',
        email: '',
        mobile: '',
      },
      // 表单内容验证规则对象
      addFromRules: {
        // 用户名验证
        username: [
          {
            required: true,
            message: '请输入用户名',
            trigger: 'blur',
          },
          {
            min: 3,
            max: 10,
            message: '请输入3~10个字符之间',
            trigger: 'blur', //失去焦点
          },
        ],
        // 密码验证
        password: [
          {
            required: true,
            message: '请输入密码',
            trigger: 'blur',
          },
          {
            min: 5,
            max: 15,
            message: '请输入5~15个字符之间',
            trigger: 'blur', //失去焦点
          },
        ],
        // 邮箱验证
        email: [
          {
            required: true,
            message: '请输入邮箱',
            trigger: 'blur',
          },
          {
            validator: checkEmail,
            trigger: 'blur',
          },
        ],
        // 手机号验证
        mobile: [
          {
            required: true,
            message: '请输入手机号',
            trigger: 'blur',
          },
          {
            validator: checkMobile,
            trigger: 'blur',
          },
        ],
      },
      editDialogVisible: false,
      // 查询到的editForm存放信息
      editForm: {},
      //  表单内容验证规则对象
      editFormRules: {
        // 邮箱验证
        email: [
          {
            required: true,
            message: '请输入邮箱',
            trigger: 'blur',
          },
          {
            validator: checkEmail,
            trigger: 'blur',
          },
        ],
        // 手机号验证
        mobile: [
          {
            required: true,
            message: '请输入手机号',
            trigger: 'blur',
          },
          {
            validator: checkMobile,
            trigger: 'blur',
          },
        ],
      },
      // 定义一个显示页面
      setRoleDialogVisible: false,
      // 所有数据
      userInfo: {},
      // 获取所有角色列表
      rolesList:[],
      
      selectedRoleId:'',
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    async getUserList() {
      const { data: res } = await this.$http.get('users', {
        params: this.queryInfo,
      })
      if (res.meta.status !== 200) return this.$message.error('读取失败')
      //把验证成功的数据保存起来
      this.userList = res.data.users
      this.total = res.data.total
      console.log(res)
    },
    // 监听pagesize  每页多少条 改变事件
    handleSizeChange(newSize) {
      // 当触发handleSizeChange时候 就把新值付给旧值
      this.queryInfo.pagesize = newSize
      // 重新渲染
      this.getUserList()
    },
    // 监听 页码值   改变事件
    handleCurrentChange(newPage) {
      // 原理同上
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },
    //监听switch 改变状态的改变
    async userStateChanged(usesinfo) {
      console.log(usesinfo)
      //发起一个put请求
      const { data: res } = await this.$http.put(
        `users/${usesinfo.id}/state/${usesinfo.mg_state}`
      )
      if (res.meta.status !== 200) {
        usesinfo.mg_state = !usesinfo.mg_state //因为失败 所以不能让他状态改变
        return this.$message.error('更新失败')
      }
      // 更改数据成功
      this.$message.success('更新数据成功')
    },
    // 监听用户对话框关闭事件
    addDialogClose() {
      //$refs.addFromRef 表单的引用 resetFields表单重置方法
      this.$refs.addFromRef.resetFields()
    },
    //点击按钮 提交新用户
    addUser() {
      // validate校验  valid校验的结果
      this.$refs.addFromRef.validate(async (valid) => {
        if (!valid) return
        // 到这里已经校验成功 接下来发起post请求 addFrom上面定义了
        const { data: res } = await this.$http.post('users', this.addFrom)
        if (res.meta.status !== 201) {
          return this.$message.error('添加失败')
        }
        //成功函数
        this.$message.success('添加成功')
        // 关闭添加窗口
        this.addDialogVisible = false
        // 重新渲染
        this.getUserList()
      })
    },
    // 展示编辑对话框
    async showEditDialog(id) {
      // 调用get
      const { data: res } = await this.$http.get('users/' + id)
      if (res.meta.status !== 200) return this.$message.error('查询失败')
      this.editForm = res.data
      this.editDialogVisible = true
    },
    // 监听用户对话框的关闭事件
    etitDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    // 修改用户提交
    editUserInfo() {
      this.$refs.editFormRef.validate(async (valid) => {
        //valid
        if (!valid) {
          return
        }
        // 发起put请求
        const { data: res } = await this.$http.put(
          'users/' + this.editForm.id,
          { email: this.editForm.email, mobile: this.editForm.mobile }
        )

        if (res.meta.status !== 200) {
          return this.$message.error('修改失败')
        }

        // 关闭对话框
        this.editDialogVisible = false
        // 重新渲染
        this.getUserList()
        // 提示
        this.$message.success('修改成功')
      })
    },
    // 根据id删除用户并提交
    async removeUserById(id) {
      const confirmRestult = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err) //这个是抛出异常

      // confirm  是确认删除  cancel 取消删除
      // console.log(confirmRestult)
      if (confirmRestult != 'confirm') {
        return this.$message.info('取消了删除')
      }
      // console.log("已经删除")
      // 发起delete请求
      const { data: res } = await this.$http.delete('users/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败')
      }

      this.$message.success('删除成功')
      // 重新渲染
      this.getUserList()
    },
    // 展示对话框
    async setRole(userInfo) {
      this.userInfo = userInfo
      //获取所有角色列表
      const {data :res}  = await this.$http.get('roles')
      if(res.meta.status !== 200){
        return this.$message.error("获取失败")
      }
      this.$message.success('获取成功')
      this.rolesList = res.data
      this.setRoleDialogVisible = true
    },
    // 提交分配角色
    async saveRoleInfo(){
      // 判断是否一样
        if(!this.selectedRoleId){
          this.$message.error('请选择需要分配的角色')
        }
        // 不一样可以添加角色了
       const {data:res} =  await this.$http.put(`users/${this.userInfo.id}/role`,{
        rid : this.selectedRoleId
       })
        if(res.meta.status !== 200){
        return this.$message.error("分配失败")
       }
        this.$message.success('分配成功')

        this.getUserList()
        //关闭对话框
        this.setRoleDialogVisible = false 

    },
    //监听提交分配规则
    setRoleDialogClose(){
      this.selectedRoleId = '',
      this.userInfo = []
    }

  },
}
</script>

<style lang="less" scoped></style>
